<template>
  <div style="overflow: hidden;">
    <div style="display: flex;justify-content: end;margin-right: 20px;"><el-button type="primary" @click="goBack">回退</el-button> </div>
    <div class="chat-container">
      <div class="chat-messages" ref="messagesContainer">
        <div v-for="(message, index) in messages" :key="index" class="message"
          :class="{ 'my-message': message.isMe, 'other-message': !message.isMe }">
          <div class="message-content">
            <div class="message-text">{{ message.text }}</div>
            <div class="message-time">{{ message.time }}</div>
          </div>
        </div>
      </div>
      <div class="input-area">
        <input v-model="newMessage" @keyup.enter="sendMessage" placeholder="输入消息..." class="message-input" />
        <button @click="sendMessage" class="send-button">发送</button>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {  getUserMessage} from '@/http/user.js'
export default {
  data() {
    return {
      newMessage: '',
      messages: [
      ],
      message: '',
      connected: false,
      error: null,
      query: {},
      $socket: '',
      baseURL: 'ws://127.0.0.1:8222'
    }
  },
  mounted() {
    this.initSocket()
    this.query = this.$route.query
    getUserMessage({ type:'all', otherId: this.query.redaId }).then(res => {
      if (res.code === 0 && res.data) {
        res.data.forEach(e => {
          console.log(e);
          
          if (e.sendId == this.query.sendId && e.readId == this.query.redaId) {
            this.messages.push({
              text: e.text,
              time: e.sendTime,
              isMe: true
            })
          }
          if (e.sendId == this.query.redaId && e.readId == this.query.sendId) {
            this.messages.push({
              text: e.text,
              time: e.sendTime,
              isMe: false
            })
          }
          this.scrollToBottom()
        });
        console.log(this.messages);
        
      }
    })
  },
  methods: {
    goBack() {
      this.$router.go(-1)
    },
    sendMessage() {
      if (!this.newMessage.trim()) return
      
      // 添加用户消息
      this.messages.push({
        text: this.newMessage,
        time: this.formatTime(),
        isMe: true
      })
      this.$socket.send(`${this.newMessage}-${this.query.sendId}-${this.query.sendName}-${this.query.redaId}-${this.query.redaName}`)
      this.newMessage = ''
      this.scrollToBottom()
    },
    formatTime(time) {
      const now = new Date();

      // 提取年、月、日、时、分、秒、毫秒
      const year = now.getUTCFullYear();
      const month = String(now.getUTCMonth() + 1).padStart(2, '0'); // 月份从 0 开始
      const day = String(now.getUTCDate()).padStart(2, '0');
      const hours = String(now.getUTCHours()).padStart(2, '0');
      const minutes = String(now.getUTCMinutes()).padStart(2, '0');
      const seconds = String(now.getUTCSeconds()).padStart(2, '0');
      const milliseconds = String(now.getUTCMilliseconds()).padStart(3, '0');

      // 拼接成目标格式
      const formattedTime = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${milliseconds}+00:00`;
      return formattedTime
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer
        container.scrollTop = container.scrollHeight
      })
    },
    initSocket() {
      this.$socket = new WebSocket(`${this.baseURL}/api/message/${this.userId}`)

      this.$socket.onopen = () => {
        console.log('Connected to server.');
      };
      this.$socket.onmessage = (event) => {
        this.messages.push({
          text: event.data,
          time: this.formatTime(),
          isMe: false
        })
      };

      this.$socket.onclose = () => {

      };
    },

  },
  computed: {
    ...mapGetters({
      userName: 'user/getUserName',
      userAvatar: 'user/getUserAvatar',
      userId: 'user/getUserId',
    }),
  }
}
</script>

<style scoped>
.chat-container {
  max-width: 800px;
  margin: 20px auto;
  border: 1px solid #ccc;
  border-radius: 8px;
  overflow: hidden;
  background-color: #f5f5f5;
}

.chat-messages {
  height: 500px;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.message {
  max-width: 70%;
  padding: 10px;
  border-radius: 15px;
}

.my-message {
  align-self: flex-end;
  background-color: #007bff;
  color: white;
}

.other-message {
  align-self: flex-start;
  background-color: white;
  border: 1px solid #ddd;
}

.message-content {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.message-text {
  word-break: break-word;
}

.message-time {
  font-size: 0.8em;
  opacity: 0.8;
}

.my-message .message-time {
  color: #e6e6e6;
}

.input-area {
  display: flex;
  padding: 20px;
  background-color: white;
  border-top: 1px solid #ddd;
}

.message-input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 20px;
  margin-right: 10px;
}

.send-button {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.send-button:hover {
  background-color: #0056b3;
}
</style>